﻿// Infrastructure/Connections/DatabaseConnectionFactory.cs

using System;
using SqlSugar;


namespace DatabaseManager.Infrastructure.Connections
{
    public class DatabaseConnectionFactory : IDatabaseConnectionFactory
    {
        private readonly string _systemConnectionString;

        public DatabaseConnectionFactory(string systemConnectionString)
        {
            if (string.IsNullOrEmpty(systemConnectionString))
                throw new ArgumentNullException(nameof(systemConnectionString));

            _systemConnectionString = systemConnectionString;
        }

        ISqlSugarClient IDatabaseConnectionFactory.CreateSystemConnection()
        {

            //ConnectionConfig connectionConfig = new ConnectionConfig();
            //connectionConfig.ConnectionString = _systemConnectionString;
            //connectionConfig.DbType = DbType.MySqlConnector;
            //connectionConfig.IsAutoCloseConnection = true;
            //connectionConfig.InitKeyType = InitKeyType.Attribute;

            //SqlSugarClient sqlSugarClient = new SqlSugarClient(connectionConfig);
            //return sqlSugarClient;

            return new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = _systemConnectionString,
                DbType = DbType.MySqlConnector,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });


        }

        ISqlSugarClient IDatabaseConnectionFactory.CreateTargetConnection(string dbType, string connectionString)
        {
            // 替换C# 8.0的switch表达式为传统switch语句
            DbType sqlDbType;
            switch (dbType?.ToLower())
            {
                case "mysql":
                    sqlDbType = DbType.MySqlConnector;
                    //sqlDbType = DbType.MySql;
                    break;
                case "sqlserver":
                    sqlDbType = DbType.SqlServer;
                    break;
                case "oracle":
                    sqlDbType = DbType.Oracle;
                    break;
                case "postgresql":
                    sqlDbType = DbType.PostgreSQL;
                    break;
                default:
                    throw new ArgumentException($"不支持的数据库类型: {dbType}");
            }

            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException(nameof(connectionString));

            return new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = connectionString,
                DbType = sqlDbType,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
        }
    }
}